// util.ts

// 本地存储相关
export const storage = {
  // 存储数据
  setItem(key: string, value: any): void {
    if (typeof value === "object") {
      localStorage.setItem(key, JSON.stringify(value));
    } else {
      localStorage.setItem(key, value as string);
    }
  },

  // 获取数据
  getItem<T>(key: string): T | null {
    const value = localStorage.getItem(key);
    if (value) {
      try {
        return JSON.parse(value) as T;
      } catch (e) {
        return value as T;
      }
    }
    return null;
  },

  // 删除数据
  removeItem(key: string): void {
    localStorage.removeItem(key);
  },

  // 清空所有本地存储
  clear(): void {
    localStorage.clear();
  },
};

// 日期格式化
export const formatDate = (
  date: Date | string | number,
  format: string = "YYYY-MM-DD HH:mm:ss",
): string => {
  const d = new Date(date);
  const map: { [key: string]: string | number } = {
    YYYY: d.getFullYear(),
    MM: (d.getMonth() + 1).toString().padStart(2, "0"),
    DD: d.getDate().toString().padStart(2, "0"),
    HH: d.getHours().toString().padStart(2, "0"),
    mm: d.getMinutes().toString().padStart(2, "0"),
    ss: d.getSeconds().toString().padStart(2, "0"),
  };

  return format.replace(/YYYY|MM|DD|HH|mm|ss/g, (matched) => map[matched]);
};

// 深拷贝对象
export const deepClone = <T>(obj: T): T => {
  return JSON.parse(JSON.stringify(obj));
};

// 获取 URL 参数
export const getQueryParam = (param: string): string | null => {
  const urlParams = new URLSearchParams(window.location.search);
  return urlParams.get(param);
};

// 防抖函数
export const debounce = (func: Function, wait: number): Function => {
  let timeout: number | null = null;
  return function (...args: any[]) {
    if (timeout) clearTimeout(timeout);
    timeout = window.setTimeout(() => func(...args), wait);
  };
};

// 节流函数
export const throttle = (func: Function, wait: number): Function => {
  let lastTime = 0;
  return function (...args: any[]) {
    const now = new Date().getTime();
    if (now - lastTime >= wait) {
      lastTime = now;
      func(...args);
    }
  };
};

// 判断是否是有效的邮箱
export const isValidEmail = (email: string): boolean => {
  const regex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
  return regex.test(email);
};

// 判断是否是有效的手机号
export const isValidPhone = (phone: string): boolean => {
  const regex = /^1[3-9]\d{9}$/;
  return regex.test(phone);
};

// 获取当前时间段
export const getTimePeriod = (): string => {
  const now = new Date();
  const hour = now.getHours();
  if (hour >= 0 && hour < 6) {
    return "凌晨";
  } else if (hour >= 6 && hour < 12) {
    return "上午";
  } else if (hour >= 12 && hour < 18) {
    return "下午";
  } else {
    return "晚上";
  }
};
